package com.example.sendmessage;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.LinkedBlockingDeque;

public class UDP {
    private static UDP instance;
    private static DatagramSocket s;
    private final int localPort = 5000;
    private static final int servicePort =5000;
    private Thread threadReceiveData, handleReceiveDataThread;
    private LinkedBlockingDeque<String> items = new LinkedBlockingDeque<>();


    public static UDP getInstance() {
        if (instance == null) {
            instance = new UDP();
        }
        return instance;
    }

    private UDP() {
        try {
            s = new DatagramSocket(localPort);
            handleReceiveData();
            receiveData();
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public static void send(String message, String ip) {
        try {
            InetAddress inetAddress = InetAddress.getByName(ip);
            int length = message.length();
            DatagramPacket packet = new DatagramPacket(message.getBytes("GB2312"), length, inetAddress, servicePort);
            s.send(packet);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void receiveData() {
        threadReceiveData = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        byte[] messageBytes = new byte[100];
                        DatagramPacket packet = new DatagramPacket(messageBytes, 100);
                        s.receive(packet);
                        items.put(new String(packet.getData(),"GB2312").trim());
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        threadReceiveData.start();
    }

    private void handleReceiveData() {
        handleReceiveDataThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        String item = items.take();
                        UDPMessage msg = new UDPMessage();
                        msg.setMsg(item);
                        EventBus.getDefault().post(msg);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        handleReceiveDataThread.start();
    }
}
